package com.nerve.cloudoffice.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.nerve.cloudoffice.common.util.JSONHelper;
import com.nerve.cloudoffice.domain.User;
import com.nerve.cloudoffice.service.ServiceExceptions;

/**
 * @project: cloudOffice
 * @file: SessionUtil.java
 * @package: com.nerve.cloudoffice.common
 * @description:
 * session helper class
 * @author: 集成显卡	1053214511@qq.com
				IBM GDC, zengxm@cn.ibm.com
 * @date&time: 2013-8-3
 * @change log:
 */
public final class SessionUtil {

	/**
	 * @method name: getLoginUser
	 * @description: 
	 * @return type: User
	 *	@return
	 */
	public static User getLoginUser(){
		HttpSession session = ServletActionContext.getRequest().getSession();
		Object obj = session.getAttribute(Const.LOGIN_USER);
		
		if(obj == null){
			/*
			//测试阶段返回id=1的user
			User u = new User();
			u.setId(1);
			return u;
			*/
			return null;
		}
		else
			return (User)obj;
	}
	
	public static void put(HttpServletRequest request,String key,Object value){
		HttpSession session=request.getSession();
		session.setAttribute(key, value);
	}
	
	public static Object get(HttpServletRequest request,String key){
		HttpSession session=request.getSession();
		return session.getAttribute(key);
	}
	
	
	/**
	 * @method name: jsonAfterIntercept
	 * @description: 默认是没有通过拦截器，所以这里的 reply 是error=true
	 * @return type: void
	 *	@param response
	 *	@param msg
	 */
	public static void jsonAfterIntercept(HttpServletResponse response, String msg){
		Reply reply = new Reply();
		reply.setError(true);
		reply.setMessage(ServiceExceptions.NO_LOGIN);
		reply.setData("LOGIN");
		
		response.setHeader("content-type", "text/plain;charset=utf-8");
		
		try{
			response.getWriter().print(JSONHelper.toJSON(reply));
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static void clearUser(HttpServletRequest request){
		HttpSession session=request.getSession();
		session.removeAttribute(Const.LOGIN_USER);
	}
}